<?php

namespace App\Http\Controllers;

use App\Events\RushedEvent;
use App\Events\ScoreChangedEvent;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class HomeController extends Controller
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $score1 = Redis::get('team-1', 0);
        $score2 = Redis::get('team-2', 0);
        return view('home', compact('score1', 'score2'));
    }

    public function score(Request $request)
    {
        $credential = $request->validate(['team' => 'required', 'type' => 'numeric|required']);
        $credential['type'] ? $credential['score'] = Redis::incr('team-'.$credential['team']) : $credential['score'] = Redis::decr('team-'.$credential['team']);
        unset($credential['type']);
        broadcast(new ScoreChangedEvent($credential));
    }

    public function rush(Request $request)
    {
//        dd(Cache::lock('rush')->release());
        $credential = $request->validate(['name' => 'required']);
        if($lock = Cache::lock('rush')){
            dd($lock);
            broadcast(new RushedEvent($credential['name']));
        }
        dd("<<<");
        return json_encode(['message' => '没抢到']);
    }
}
